package com.bittech.client.service;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.PrintStream;

/**
 * @Author: yuisama
 * @Date: 2019-06-13 15:14
 * @Description:
 */
public class ChatGUI {
    private JPanel chatGUI;
    private JTextArea readFromServer;
    private JTextField send2Server;
    // 标题名称
    private String privateChatClient;
    // 自己名称
    private String myName;
    private Connect2Server connect2Server;
    private PrintStream out;
    private JFrame frame;




    public ChatGUI(String privateChatClient,String myName,Connect2Server connect2Server) {
        this.connect2Server = connect2Server;
        this.myName = myName;
        this.privateChatClient = privateChatClient;
        out = new PrintStream(connect2Server.getClientWrite());
        frame = new JFrame("与"+ privateChatClient +"聊天中...");
        frame.setContentPane(chatGUI);
        frame.setSize(400,400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setVisible(true);

        // 捕捉TextField回车事件，输出到TextArea以及Server
        send2Server.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                StringBuilder sb = new StringBuilder();
                sb.append(send2Server.getText());
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    // 输出到服务端与TextArea
                    String str = sb.toString();
                    String outToServer = "P:"+ privateChatClient+"_"+myName+"-"+str;
                    System.out.println("发送到服务器的信息为:"+outToServer);
                    out.println(outToServer);
                    readFromServer.append(myName+"说:"+str+"\n");
                    send2Server.setText("");
                }
            }
        });
    }

    public void readFromServer(String msg) {
        System.out.println("服务器发来的私聊信息为"+msg);
        // 将内容输出到TextArea
        readFromServer.append(msg+"\n");
    }

    public JFrame getFrame() {
        return frame;
    }
}
